#include "inputusers.h"
#include "ui_inputusers.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QFile>
#include <QTextStream>
#include "url_string.h"
#include "common.h"

extern std::string      g_token;
extern std::string      g_url;

void InputUsersThread::setFilePath(QString path)
{
    m_filepath = path;
}

void InputUsersThread::setGID(int gid)
{
    m_gid = gid;
}

void InputUsersThread::run()
{
    UserData            data;

    if(false == getUsers(data))
    {
        emit onInfo("读取文件失败");
        return;
    }

    sendToServer(data);
    emit onEnd();
}

// [name]<t>[phone]<t>[email]<t>[qq]<t>[msn]
bool InputUsersThread::getUsers(UserData &data)
{
    char*   buf     = ad::get_file_data(m_filepath.toLocal8Bit().data());
    char*   saveline = NULL;
    char*   line;

    if(NULL == buf)
    {
        return false;
    }

    for(char* sl = buf;
        (line = strtok_r(sl, "\r\n", &saveline)) != NULL;
        sl = NULL)
    {
        // read line
        std::vector< std::string >  vct;
        char*                       saveitem    = NULL;
        char*                       item;
        char*                       si          = line;

        for(int i = 0; i < 5; i++, si = NULL)
        {
            if((item = strtok_r(si, "\t", &saveitem)) != NULL)
            {
                vct.push_back(item);
            }
            else
            {
                vct.push_back("");
            }
        }

        data.push_back( vct );
    }

    free(buf);
    return data.size() > 0;
}

// [name]<t>[phone]<t>[email]<t>[qq]<t>[msn]
void InputUsersThread::sendToServer(UserData &data)
{
    for(int i = 0;
        i < (int)data.size();
        i++, emit onPrograss(i * 100 / data.size()))
    {
        url_string<>        url;
        url_string<>        post;
        QByteArray          byte;
        QString             err;

        url.format("%s?Handler=adduser&token=%u", g_url.c_str(), g_token.c_str());
        post.format("gid=%d&name=%u&email=%u&phone=%u&qq=%u&msn=%u",
                    m_gid,
                    data[i][0].c_str(),
                    data[i][2].c_str(),
                    data[i][1].c_str(),
                    data[i][3].c_str(),
                    data[i][4].c_str()
                    );
        byte.append(post.c_str(), post.length());
        ad::http_request(url.c_str(), err, NULL, NULL, &byte);
    }
}

///////////////////////////////////////////////////////////////////////////
InputUsers::InputUsers(int gid, QString group, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::InputUsers),
    m_gid(gid)
{
    m_isinputing = false;

    ui->setupUi(this);
    setWindowTitle(_T("批量导入"));

    ui->progressBar->hide();
    //ui->listView->hide();
    //ui->textBrowser->hide();

    ui->infoGroup->setText(_T("<h2>批量导入组\"") + group + _T("\"的用户</h2>"));
}

InputUsers::~InputUsers()
{
    delete ui;
    if(m_thread.isRunning())
    {
        m_thread.terminate();
        m_thread.wait();
    }
}

void InputUsers::onFindFile()
{
    QString filename = QFileDialog::getOpenFileName(this, tr("open file"),
                                                    " ",
                                                    tr("Allfile(*.*)"));
    if(filename.size() > 0)
    {
        ui->lineEdit->setText(filename);
    }
}

void InputUsers::onBeginInput()
{
    if(0 == ui->lineEdit->text().size())
    {
        QMessageBox     box(this);

        box.setText(_T("请选择数据文件所在路径"));
        box.setIcon(QMessageBox::Critical);
        box.exec();
        return;
    }

    ui->progressBar->show();
    ui->progressBar->setValue(0);
    ui->btnInput->setDisabled(true);

    connect(&m_thread, SIGNAL(onEnd()), this, SLOT(accept()));
    connect(&m_thread, SIGNAL(onPrograss(int)), ui->progressBar, SLOT(setValue(int)));
    connect(&m_thread, SIGNAL(onInfo(QString)), this, SLOT(onInfo(QString)));

    m_thread.setFilePath(ui->lineEdit->text());
    m_thread.setGID(m_gid);
    m_thread.start();
}

void InputUsers::onCancel()
{
    if(false == m_isinputing)
    {
        this->close();
        return;
    }
}

void InputUsers::onInfo(QString info)
{
    QMessageBox     msg(this);

    msg.setText(info);
    msg.setIcon(QMessageBox::Information);
    msg.exec();
    close();
}

